<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="分类状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:category:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:category:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:category:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:category:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      ref="categoryTable"
      v-loading="loading" 
      :data="categoryList" 
      @selection-change="handleSelectionChange"
      row-key="categoryId"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :default-expand-all="false"
      :row-class-name="tableRowClassName"
      border
      :header-cell-style="getHeaderCellStyle">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类名称" align="left" prop="categoryName" min-width="200">
        <template slot-scope="scope">
          <span :style="{paddingLeft: (scope.row.level - 1) * 20 + 'px'}">
            <svg v-if="scope.row.level === 1" style="width: 16px; height: 16px; margin-right: 8px; vertical-align: middle;" viewBox="0 0 1024 1024">
              <path fill="#409EFF" d="M853.333 469.333A42.667 42.667 0 0 0 810.667 426.667H663.25l-67.584-135.168A64 64 0 0 0 538.583 256H213.333A42.667 42.667 0 0 0 170.667 298.667v426.666A42.667 42.667 0 0 0 213.333 768h597.334A42.667 42.667 0 0 0 853.333 725.333V469.333z"/>
            </svg>
            <svg v-else style="width: 14px; height: 14px; margin-right: 8px; vertical-align: middle;" viewBox="0 0 1024 1024">
              <path fill="#67C23A" d="M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM790.2 326H602V137.8L790.2 326z m-366 170v60c0 4.4-3.6 8-8 8h-60c-4.4 0-8-3.6-8-8v-60c0-4.4 3.6-8 8-8h60c4.4 0 8 3.6 8 8z m0 204v60c0 4.4-3.6 8-8 8h-60c-4.4 0-8-3.6-8-8v-60c0-4.4 3.6-8 8-8h60c4.4 0 8 3.6 8 8z m308-204v60c0 4.4-3.6 8-8 8H500c-4.4 0-8-3.6-8-8v-60c0-4.4 3.6-8 8-8h224c4.4 0 8 3.6 8 8z m0 204v60c0 4.4-3.6 8-8 8H500c-4.4 0-8-3.6-8-8v-60c0-4.4 3.6-8 8-8h224c4.4 0 8 3.6 8 8z"/>
            </svg>
            <span v-if="isSearchMatch(scope.row.categoryName)" v-html="highlightSearchText(scope.row.categoryName)"></span>
            <span v-else>{{ scope.row.categoryName }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="层级" align="center" prop="level">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.level === 1" type="primary" size="small">一级</el-tag>
          <el-tag v-else type="success" size="small">二级</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddSub(scope.row)"
            v-hasPermi="['system:category:add']"
            v-if="scope.row.level === 1"
          >添加子分类</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:category:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:category:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    


    <!-- 添加或修改宠物分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/system/category";

export default {
  name: "Category",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 宠物分类表格数据（树形结构）
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为编辑模式
      isEditMode: false,
      // 查询参数
      queryParams: {
        categoryName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        sortOrder: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 表头样式设置 */
    getHeaderCellStyle({ column, columnIndex }) {
      const colors = [
        'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', // 深蓝紫渐变
        'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)', // 粉红渐变
        'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)', // 蓝青渐变
        'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)', // 绿青渐变
        'linear-gradient(135deg, #fa709a 0%, #fee140 100%)', // 粉黄渐变
        'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)', // 青粉渐变
        'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)', // 橙粉渐变
        'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)', // 红粉渐变
        'linear-gradient(135deg, #a18cd1 0%, #fbc2eb 100%)', // 紫粉渐变
        'linear-gradient(135deg, #fad0c4 0%, #ffd1ff 100%)'  // 桃粉渐变
      ];
      return {
        background: colors[columnIndex % colors.length],
        color: '#333333',
        fontWeight: 'bold',
        textAlign: 'center',
        fontSize: '14px',
        borderRight: '1px solid rgba(255,255,255,0.3)',
        position: 'relative'
      }
    },
    /** 判断是否匹配搜索关键词 */
    isSearchMatch(text) {
      return this.queryParams.categoryName && 
             text && 
             text.includes(this.queryParams.categoryName);
    },
    /** 高亮显示搜索关键词 */
    highlightSearchText(text) {
      if (!this.queryParams.categoryName || !text) {
        return text;
      }
      
      const searchKeyword = this.queryParams.categoryName;
      const regex = new RegExp(`(${searchKeyword})`, 'gi');
      return text.replace(regex, '<span class="highlight-mark">$1</span>');
    },
    /** 表格行样式 */
    tableRowClassName({row, rowIndex}) {
      if (this.isSearchMatch(row.categoryName)) {
        return 'search-result-row';
      }
      return '';
    },
    /** 查询宠物分类列表（树形结构） */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.data || [];
        this.loading = false;
        
        // 如果是搜索操作且有搜索关键词，自动展开包含搜索结果的父级分类
        if (this.queryParams.categoryName) {
          this.$nextTick(() => {
            // 遍历所有分类，找到二级分类并展开其父级
            const expandParentIds = [];
            const findAndExpandParents = (categories) => {
              categories.forEach(category => {
                // 如果是二级分类且匹配搜索关键词，则记录其父级ID
                if (category.level === 2 && 
                    category.categoryName && 
                    category.categoryName.includes(this.queryParams.categoryName)) {
                  if (category.parentId) {
                    expandParentIds.push(category.parentId);
                  }
                }
                
                // 递归处理子分类
                if (category.children && category.children.length > 0) {
                  findAndExpandParents(category.children);
                }
              });
            };
            
            findAndExpandParents(this.categoryList);
            
            // 展开所有需要展开的父级分类
            expandParentIds.forEach(parentId => {
              this.$refs.categoryTable.toggleRowExpansion({ categoryId: parentId }, true);
            });
          });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: null,
        categoryName: null,
        sortOrder: 0,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.categoryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEditMode = false;
      this.open = true;
      this.title = "添加宠物分类";
    },
    /** 添加子分类操作 */
    handleAddSub(row) {
      this.reset();
      // 设置父级分类ID，确保添加的是子分类
      this.form.parentId = row.categoryId;
      this.isEditMode = false;
      this.open = true;
      this.title = `添加"${row.categoryName}"的子分类`;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEditMode = true;
      const categoryId = row.categoryId || this.ids
      getCategory(categoryId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改宠物分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.categoryId != null) {
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              // 通知其他组件重新加载分类数据
              this.$root.$emit('categoryChanged');
            });
          } else {
            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 通知其他组件重新加载分类数据
              this.$root.$emit('categoryChanged');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const categoryIds = row.categoryId || this.ids;
      this.$modal.confirm('是否确认删除宠物分类编号为"' + categoryIds + '"的数据项？').then(function() {
        return delCategory(categoryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/category/export', {
        ...this.queryParams
      }, `category_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
/* 确保表格样式稳定 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表头样式增强 */
::v-deep .el-table__header-wrapper {
  border-radius: 8px 8px 0 0;
}

::v-deep .el-table__header th {
  border-right: 1px solid rgba(255,255,255,0.3) !important;
  position: relative;
}

::v-deep .el-table__header th:before {
  content: '';
  position: absolute;
  top: 50%;
  right: 0;
  width: 1px;
  height: 60%;
  background: rgba(255,255,255,0.3);
  transform: translateY(-50%);
}

::v-deep .el-table__header th:last-child:before {
  display: none;
}

/* 行样式优化 */
::v-deep .el-table__row {
  transition: all 0.3s ease;
}

::v-deep .el-table__row:hover {
  background-color: #f8f9ff !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* 树形表格缩进样式优化 */
.tree-category-name {
  display: flex;
  align-items: center;
  font-weight: 500;
}

/* 图标样式优化 */
.category-icon {
  margin-right: 8px;
  transition: all 0.3s ease;
}

.category-icon:hover {
  transform: scale(1.1);
}

/* 标签样式优化 */
::v-deep .el-tag {
  border-radius: 12px;
  font-weight: 500;
}

/* 对话框样式优化 */
::v-deep .el-dialog__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px 8px 0 0;
  padding: 20px;
}

::v-deep .el-dialog__title {
  color: white;
  font-weight: bold;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
  color: white;
  font-size: 18px;
}

::v-deep .el-dialog {
  border-radius: 8px;
  overflow: hidden;
}

/* 搜索高亮样式 */
.highlight-mark {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  color: #fff;
  padding: 2px 4px;
  border-radius: 4px;
  font-weight: bold;
  box-shadow: 0 2px 4px rgba(255, 154, 158, 0.3);
}

/* 搜索结果行样式 */
::v-deep .el-table__row.search-result-row {
  background-color: #fff9f9 !important;
  border-left: 3px solid #ff9a9e;
}
</style>